<!-- 通用的分类组件 -->
<template>
  <div class="p-5">
    <!-- <div class="card-box">
      <SearchView @query="querybtn" @reset="resetbtn" />
    </div> -->

    <div class="card-box box mt-5">
      <a-button type="primary" @click="openbtn(null)">
        <template #icon>
          <PlusOutlined />
        </template>新增分类
      </a-button>
      <a-table :columns="columns" :data-source="data" :pagination="false" :loading="loading" rowKey="value">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'icon'">
            <a-image :width="100" :src="record.extend.icon" />
          </template>
          <template v-if="column.key === 'description'">
            <span>{{ record.extend?.description }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" primary @click="editbtn(record)">编辑</a-button>
            <a-button type="link" danger @click="deleteBtn(record.value)">删除</a-button>
          </template>
        </template>
      </a-table>
      <PageView />
    </div>
    <addView v-model:value="newdata.open" :catalist="data" :type="newdata.type" :editdata="newdata.editinfo"
      @submit="submitbtn" />
  </div>
</template>
<script setup lang="ts">
import { reactive, onMounted, createVNode } from "vue";

import { PlusOutlined, ExclamationCircleOutlined } from "@ant-design/icons-vue";
import * as api from "#/api/core/class.ts";

import addView from "./addView.vue";
import SearchView from "./searchView.vue";

import PageView from "#/components/PageView/index.vue";
import { useRequest, createUseRequestComponent } from "vue-hooks-plus";
import { Modal } from "ant-design-vue";
import { message } from "ant-design-vue";

const props = defineProps({
  types: {
    type: Number,
    defalut: 1,
  },
});

// 定义接口类型
interface NewData {
  type: "add" | "update"; // 限制 type 只能是 'add' 或 'edit'
  editinfo: any; // 根据实际情况替换 any 为具体类型，比如 YourEditInfoType
  open: boolean;
  current: number;
  pagesize: number;
  query: any;
}

const newdata: NewData = reactive({
  open: false,
  type: "add",
  editinfo: {},
  current: 1,
  pagesize: 20,
  query: {},
});

const columns = [
  {
    title: "图标",
    dataIndex: "icon",
    align: "center",
    key: "icon",
    width: 400,
  },
  {
    title: "名称",
    dataIndex: "label",
    align: "center",
    key: "label",
  },
  {
    title: "描述",
    dataIndex: "description",
    align: "center",
    key: "description",
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
    key: "action",
  },
];
const datas = [
  {
    id: 1,
    name: "营养知识",
    desc: "描述",
  },
  {
    id: 2,
    name: "健康生活",
    desc: "描述",
  },
];

const openbtn = (e: any) => {
  newdata.type = "add";
  newdata.editinfo = e;
  newdata.open = true;
};


function findAllParentValues(data, targetValue) {
  // 存储父级节点路径的数组
  const parentPath = [];

  // 递归查找函数
  function searchNodes(nodes) {
    for (const node of nodes) {
      // 如果找到目标节点，返回true表示找到
      if (node.value === targetValue) {
        return true;
      }

      // 如果有子节点，递归查找
      if (node.children && node.children.length > 0) {
        // 先将当前节点加入路径（假设是父级）
        parentPath.push(node.value);
        // 递归查找子节点
        const found = searchNodes(node.children);

        if (found) {
          // 找到目标，保持当前路径
          return true;
        } else {
          // 未找到，移除当前节点（不是父级）
          parentPath.pop();
        }
      }
    }
    // 未找到目标
    return false;
  }

  // 执行查找
  const found = searchNodes(data);

  // 如果找到目标，返回父级路径数组；否则返回null
  return found ? parentPath : null;
}

const editbtn = (e: any) => {
  newdata.type = "update";
  newdata.editinfo = {
    ...e,
    parentid: findAllParentValues(data.value, e.value)
  }
  console.log('编辑', newdata.editinfo);

  newdata.open = true;
};

const querybtn = (e: any) => {
  console.log("e", e);
  newdata.query = e;
  run();
};

const resetbtn = (e: any) => {
  newdata.query = e;
  run();
};

const { data, loading, error, run } = useRequest(
  () =>
    api.$getalllist({

      type: props.types,
    }),
  {
    manual: true, //手动触发
    onSuccess: (result) => {
      console.log("获取分类数据", result);
      // 此时 data.value 与 result 是一致的
      console.log("data.value：", data.value);
    },
  }
);

run();

const submitbtn = () => {
  newdata.current = 1;
  run();
};

const deleteBtn = (id) => {
  Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "确定要删除该分类?",
    async onOk() {
      try {
        await api.$deleteclass({}, id);
        message.success("删除成功");
        newdata.current = 1;
        run();
      } catch { }
    },
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    onCancel() { },
  });
};






</script>
<style scoped lang="less">
.box {
  min-height: 100px;
  // box-sizing: border-box;
  // padding: 20px;
}
</style>
